from PySide6.QtCore import QObject, Signal, QMutex, QWaitCondition, QMutexLocker
from AppCore import YamlHandler


class ResourceLoader(QObject):
    progress_updated = Signal(int)  # 进度更新信号
    finished = Signal()  # 完成信号
    error_occurred = Signal(str)  # 新增错误信号

    def __init__(self):
        super().__init__()
        self.value = 0
        self._paused = False
        self._stopped = False
        self._lock = QMutex()
        self._cond = QWaitCondition()
        self.sys_config = {}
        self.load_config()

    def load_config(self):
        self.loading_config = YamlHandler("res/loading_config.yml")
        self._base_paths = self.loading_config["base_path"]

    def stop(self):
        with QMutexLocker(self._lock):
            self._stopped = True

    def resume(self):
        if self._paused:
            with QMutexLocker(self._lock):
                self._paused = False
                self._cond.wakeOne()

    def send_progress(self, value):
        self.progress_updated.emit(value)

    def perform_loading(self):
        try:
            for category, steps in self.loading_config["loading_steps"].items():
                for step in steps:
                    self._load_step(step, category)
            print(
                f'{self.sys_config["app_lang"]["SYS"]["sys_name"]}-{self.sys_config["app_lang"]["SYS"]["sys_copyright"]}'
            )
            self.finished.emit()
        except Exception as e:
            self.error_occurred.emit(f"加载失败: {str(e)}")

    def _load_step(self, step_config, category):
        full_path = f"{self._base_paths[category]}{step_config['path']}"
        data = YamlHandler(full_path)
        # print(data)
        if step_config.get("merge"):
            existing = self.sys_config[step_config["target"]]
            existing.merge(data)
            # print(f"合并 {step_config['target']} 完成")
            self.sys_config[step_config["target"]] = existing
        else:
            # print(f"创建 {step_config['target']} 完成")
            self.sys_config[step_config["target"]] = data
        self.send_progress(step_config["progress"])
        self._paused = True
        with QMutexLocker(self._lock):
            while self._paused:
                self._cond.wait(self._lock)
